package com.xh.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * description: WebSocketServer <br>
 * date: 2021/11/14 1:21 <br>
 * author: xiehui <br>
 * version: 1.0 <br>
 */

public class WebSocketServer {
    public static void main(String[] args)  {
        // 创建一组线程池组
        // 主线程池：用于接收客户端的连接，不做其他处理
        EventLoopGroup bossGroup = new NioEventLoopGroup();

        // 从线程池：接收主线程池的任务，实际做任务
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建服务器启动类
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup,workerGroup)// 设置主从线程组
                    .channel(NioServerSocketChannel.class) // 设置nio双向通道
                    .childHandler(new WSServerInitializer());// 添加子处理器，用于处理从线程池里面的任务

            // 启动服务，并设置端口号，同时启动方式为同步
            ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();
            // 监听关闭的channel，设置为同步方式
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
